package com.dx.service.impl;

import com.dx.pojo.LogInfo;
import com.dx.service.LogService;
import com.dx.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @program: Isp_Automatic_punch
 * @description:
 * @author: hanabi
 * @create: 2022-02-09 21:49
 **/
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;
    @Value("${mail.fromMail.addr}")
    private String from;

    @Autowired
    private LogService logService;

    @Override
    public void sendMail(String to, String subject, String content) {
        if (null == to || "".equals(to)) {
            log.info("==>email receiver is null ");
            return;
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(from);
        try {
            mailSender.send(message);
            log.info("==>sending email to " + to);
            LogInfo logInfo = new LogInfo();
            logInfo.setEmail(to);
            logInfo.setDate(System.currentTimeMillis());
            logInfo.setInfo(content);
            logService.save(logInfo);
        } catch (MailException e) {
            e.printStackTrace();
            log.error("==>sending email failed of" + to);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("==>sending email error");
            return;
        }
        log.info("==>email successfully sended");
    }
}
